package com.cgah

import com.cgah.Constants
import grails.converters.JSON

//        NOTES TO SELF
//        see http://grails.org/doc/latest/guide/6.%20The%20Web%20Layer.html for explantion of
//        how the model, view and controller work together.

class ListingController {
    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
    def springSecurityService

    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
        // M-2: The main landing page shows up to 5 listings at a time
        params.max = Math.min(params.max ? params.int('max') : Constants.MAX_TO_DISPLAY, 100)
        //M-1: The main landing page shows listings sorted by the date they were created (most recent first)
        if (!params.sort) params.sort = "createdDateTime"
        if (!params.order) params.order = "desc"
        if (!params.offset) params.offset = 0;

        // the list.gsp view has access to listingInstanceList and listingInstanceTotal as models
        // also since no explicit view is defined list.gsp is the view by convention.
        // f'ng findAll won't convert from string to int hence the .toInteger()
        //
        // M-4: Only listings with a end date/time that is in the future are visible on the main page

        def result = Listing.findAll("from Listing as l where l.endDateTime > sysdate order by " + params.sort + " " + params.order,  // can you say fail?
                                        [max:params.max?.toInteger(), offset:params.offset?.toInteger()]);
        [listingInstanceList: result ];

    }

    def myListings = {
        // S-5: Create a view called "My Listings" that shows listings created by the logged in user
        params.max = Math.min(params.max ? params.int('max') : Constants.MAX_TO_DISPLAY, 100)

        if (!params.sort) params.sort = "createdDateTime"
        if (!params.order) params.order = "desc"
        if (!params.offset) params.offset = 0;

        def result = Listing.findAll("from Listing as l inner join l.seller as s where s.username = '" + springSecurityService.authentication.name +"'") //+ " order by " + params.sort + " " + params.order,  // can you say fail?
                                        //[max:params.max?.toInteger(), offset:params.offset?.toInteger()]);
        //def result = Listing.findAll("from Listing as l inner join l.seller as s ") //order by " + params.sort + " " + params.order,  // can you say fail?
                                        //[max:params.max?.toInteger(), offset:params.offset?.toInteger()]);
        [listingInstanceList: result ];
    }

    def create = {
        def listingInstance = new Listing()
        listingInstance.properties = params
        return [listingInstance: listingInstance]
    }

    def save = {
        def listingInstance = new Listing(params)
        if (listingInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'listing.label', default: 'Listing'), listingInstance.id])}"
            redirect(action: "show", id: listingInstance.id)
        }
        else {
            render(view: "create", model: [listingInstance: listingInstance])
        }
    }

    def show = {
        def listingInstance = Listing.get(params.id)
        if (!listingInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'listing.label', default: 'Listing'), params.id])}"
            redirect(action: "list")
        }
        else {
            Calendar now = Calendar.getInstance();

            if (listingInstance.endDateTime.before(now)) {
                render(view: "expired", model: [listingInstance: listingInstance])
            } else {
                [listingInstance: listingInstance]
            }
        }
    }

    def edit = {
        def listingInstance = Listing.get(params.id)
        if (!listingInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'listing.label', default: 'Listing'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [listingInstance: listingInstance]
        }
    }

    def update = {
        def listingInstance = Listing.get(params.id)
        if (listingInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (listingInstance.version > version) {
                    
                    listingInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'listing.label', default: 'Listing')] as Object[], "Another user has updated this Listing while you were editing")
                    render(view: "edit", model: [listingInstance: listingInstance])
                    return
                }
            }
            listingInstance.properties = params
            if (!listingInstance.hasErrors() && listingInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'listing.label', default: 'Listing'), listingInstance.id])}"
                redirect(action: "show", id: listingInstance.id)
            }
            else {
                render(view: "edit", model: [listingInstance: listingInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'listing.label', default: 'Listing'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def listingInstance = Listing.get(params.id)
        if (listingInstance) {
            try {
                listingInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'listing.label', default: 'Listing'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'listing.label', default: 'Listing'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'listing.label', default: 'Listing'), params.id])}"
            redirect(action: "list")
        }
    }

    def user = {
        // TODO: filter by user
        // M-2: The main landing page shows up to 5 listings at a time
        params.max = Math.min(params.max ? params.int('max') : Constants.MAX_TO_DISPLAY, 100)
        //M-1: The main landing page shows listings sorted by the date they were created (most recent first)
        if (!params.sort) params.sort = "createdDateTime"
        if (!params.order) params.order = "desc"
        if (!params.offset) params.offset = 0;

        // the list.gsp view has access to listingInstanceList and listingInstanceTotal as models
        // also since no explicit view is defined list.gsp is the view by convention.
        // f'ng findAll won't convert from string to int hence the .toInteger()
        //
        // M-4: Only listings with a end date/time that is in the future are visible on the main page

        def result = Listing.findAll("from Listing as l where l.endDateTime > sysdate order by " + params.sort + " " + params.order,  // can you say fail?
                                        [max:params.max?.toInteger(), offset:params.offset?.toInteger()]);
        [listingInstanceList: result ];

    }



    // WE DO NOT SUPPORT XML
    def lastTenBids = {

        List<BidJsonResponse> bidJsonResponseList = new ArrayList();

        def listingInstance = Listing.get(params.id)
        // WTF this shit don't work so i'm manually fetching each customer f'it! wasted too much time
        def lastTen =  Bid.lastTen(listingInstance).list(max: 10, fetch:[customer:"eager"]); //Bid.list(max: 10, fetch:[customer:"eager"]);//;

        for (Bid b : lastTen) {
            bidJsonResponseList.add(new BidJsonResponse(b.id, b.amount, b.nextMinBid, b.dateTime, Customer.get(b.customer.id).username));
        }
        render bidJsonResponseList as JSON;
    }
}
